package com.fise.mwtvc

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Instrumentation
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.media.AudioManager
import android.os.IBinder
import android.os.PowerManager
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
import android.view.Surface

import java.lang.reflect.InvocationTargetException
import java.util.*


object AndroidUtils {

    private const val TAG = "AndroidUtils"
    fun getVersionCode(): Int {
        val context: Context = ContextProvider.get().context
        val packInfo = context.packageManager.getPackageInfo(context.packageName, 0)
        return packInfo.versionCode
    }

    fun getAppMetaDataString(context: Context, metaName: String): String {
        //application标签下用getApplicationinfo，如果是activity下的用getActivityInfo
        return context.packageManager.getApplicationInfo(
            context.packageName,
            PackageManager.GET_META_DATA
        ).metaData.getString(metaName, "normal")
    }

    @SuppressLint("SuspiciousIndentation")
    fun reboot() {
        val intent = Intent("com.fise.system.reboot")
        intent.setPackage(ContextProvider.get().context.packageName)
         ContextProvider.get().context.sendStickyBroadcast(intent)
     }

    fun getRunningAppPkName(): String {
        val context = ContextProvider.get().applicationContext
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        am.runningAppProcesses?.let {
            for (ra in it) {
                if (ra.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE
                    || ra.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                ) {
                    return ra.processName
                }
            }
        }
        return "";
    }

    fun getForegroundActivity(): String {
        val context = ContextProvider.get().applicationContext
        val mActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        if (mActivityManager.getRunningTasks(1) == null) {
            return ""
        }
        val mRunningTask = mActivityManager.getRunningTasks(1)[0] ?: return ""
        //String activityName =  mRunningTask.topActivity.getClassName();
        //String packageName =  mRunningTask.topActivity!!.packageName
        return mRunningTask.topActivity!!.className
    }

    fun screenshot(): Bitmap? {
        val context = ContextProvider.get().applicationContext
        val resources: Resources = context.resources
        val dm: DisplayMetrics = resources.displayMetrics
        var surfaceClassName = ""
        surfaceClassName = "android.view.SurfaceControl"
        try {
            val mClassType = Class.forName(surfaceClassName)
            val method = mClassType.getDeclaredMethod(
                "screenshot",
                Rect::class.java,
                Int::class.javaPrimitiveType,
                Int::class.javaPrimitiveType,
                Int::class.javaPrimitiveType
            )
            method.isAccessible = true
            return method.invoke(
                mClassType,
                Rect(),
                dm.widthPixels,
                dm.heightPixels,
                Surface.ROTATION_0
            ) as Bitmap
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun screenshot2() {
        val inst = Instrumentation();
        try {
            inst.sendKeyDownUpSync(120);
        } catch (e: Exception) {
            Log.e("AndroidUtils", "事件出现异常" + e.message);
        }
    }

    fun getAppIcon(pakgename: String): Drawable? {
        val context = ContextProvider.get().applicationContext
        val pm: PackageManager = context.packageManager
        try {
            val appInfo = pm.getApplicationInfo(pakgename, PackageManager.GET_META_DATA)
            return pm.getApplicationIcon(appInfo)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }



    fun shutdown() {

        try {
            val pManager =
                ContextProvider.get().applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
            val method = pManager.javaClass.getMethod(
                "shutdown",
                Boolean::class.javaPrimitiveType,
                String::class.java,
                Boolean::class.javaPrimitiveType
            )
            method.invoke(pManager, false, "", true)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    fun rebootSafeMode() {

        try {
            val pManager =
                ContextProvider.get().applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
            val method = pManager.javaClass.getMethod(
                "rebootSafeMode"
             )
            method.invoke(pManager)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    fun shutdown(comd1:Boolean,cmd2:String,cmd3:Boolean) {

        try {
            val pManager =
                ContextProvider.get().applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
            val method = pManager.javaClass.getMethod(
                "shutdown",
                Boolean::class.javaPrimitiveType,
                String::class.java,
                Boolean::class.javaPrimitiveType
            )
            method.invoke(pManager, comd1, cmd2, cmd3)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    fun getCurrentLanguage(): String {
        val context = ContextProvider.get().applicationContext
        val language = Locale.getDefault().language
//        Log.i("AndroidUtils", "current language: $language")
        val currentLocale: Locale = context.resources.getConfiguration().locale
        val language2 = currentLocale.language
//        Log.i("AndroidUtils", "current language2: $language2")
        return if ("en" == language) {
            "en"
        } else {
            "zh"
        }
    }

    fun getBrightnessValue(): Int {
        var cResolver: ContentResolver? =  ContextProvider.get().context.getContentResolver();

        val brightness: Int = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS)
        return brightness
    }

    fun getVoiceValue(): Int {


        val audioManager = ContextProvider.get().context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)


    }


    /**
     * 系统操作
     */
    fun systemOperation(name: String) {
        try {
            //获得ServiceManager类
            val ServiceManager = Class.forName("android.os.ServiceManager")
            //获得ServiceManager的getService方法
            val getService = ServiceManager.getMethod("getService", String::class.java)
            //调用getService获取RemoteService
            val oRemoteService = getService.invoke(null, Context.POWER_SERVICE)
            //获得IPowerManager.Stub类
            val cStub = Class.forName("android.os.IPowerManager\$Stub")
            //获得asInterface方法
            val asInterface = cStub.getMethod("asInterface", IBinder::class.java)
            //调用asInterface方法获取IPowerManager对象
            val oIPowerManager = asInterface.invoke(null, oRemoteService)

            for (method in oIPowerManager.javaClass.methods) {
                Log.i("SystemUtil", "方法名：" + method.name)
                //获取本方法所有参数类型，存入数组
                val getTypeParameters = method.parameterTypes
                if (getTypeParameters.isEmpty()) {
                    Log.i("SystemUtil", "此方法无参数")
                }
                for (class1 in getTypeParameters) {
                    val parameterName = class1.name
                    Log.i("SystemUtil", "参数类型：$parameterName")
                }
                Log.i("SystemUtil", "****************************")
            }

            val method = oIPowerManager.javaClass.getMethod(
                name,
                Boolean::class.java,
                String::class.java,
                Boolean::class.java
            )
            method.invoke(oIPowerManager, false, null, false)

        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }



}